#!/usr/bin/env python
# -*- coding:utf-8 -*-
#


import socket
import threading
import SocketServer
import json
import time
import binascii
import getopt,sys
def usage():
    print '''
	server.py usage:
	-t,--tcp   :tcp protocol
	-u,--udp   :udp protocol
	-s,--server:contect ip ,like 192.168.1.1
	-p,--port  :contect port,like 10000
	-d,--data  :ascii data
	-h,--hexdata:hex data
	  '''
def tcpclient(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    try:
        print "Send: {}".format(message)
        sock.sendall(message)
        response = sock.recv(1024)
        print "Recv: ",response
    finally:
        sock.close()

def udpclient(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.connect((ip, port))
    try:
        print "Send: {}".format(message)
        sock.sendall(message)
        #response = sock.recv(1024)
        #print "Recv: ",response
    finally:
        sock.close()

def main(argv):
    shortargs='x:s:p:d:h'
    longargs=['xieyi','server','port','data','hexdata']
    server=None
    port=None
    data=None
    protocol=None 
    try:
	opts,args=getopt.getopt(argv[1:],shortargs,longargs)
	for opt,val in opts:
	    if opt=='-s' or opt=='--server':
		server=val
	    elif opt=='-p' or opt=='--port':
		port=int(val)
	    elif opt=='-d' or opt=='--data':
		data=val
	    elif opt=='-h' or opt=='--hexdata':
		data=binascii.a2b_hex(val)
	    elif opt=='-x':
		protocol=val
    # Port 0 means to select an arbitrary unused port
    except Exception,e:
	usage()
	print e
    HOST, PORT = server,port
    if HOST==None or PORT==None or protocol==None:
	usage()
	sys.exit(2)
    # Port 0 means to select an arbitrary unused port
    jmsg1='tcp test packages'
    jmsg2='udp test packages'
    jmsg1=binascii.a2b_hex('7e02')
    if protocol=='tcp':
        tcpthread=tcpclient(HOST, PORT, jmsg1)
    elif protocol=='udp':
        udpthread=udpclient(HOST, PORT, jmsg2)
    else:
	print 'please chose protocol'
	usage()

if __name__ == "__main__":
    main(sys.argv)
